package xyz.fefine;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * 用于记录全局变量，可变长度
 * 能通过编号和变量名查值
 * Created by feng_ on 2016/9/17.
 */
public class ResizableArrayEnv extends ArrayEnv {
    protected Symbols names;

    public ResizableArrayEnv() {
        super(10, null);
        names = new Symbols();
    }

    @Override
    public Object get(int nest, int index) {
        return super.get(nest, index);
    }

    @Override
    public Symbols symbols() {
        return super.symbols();
    }

    @Override
    public void put(int nest, int index, Object value) {
        if (nest == 0) {
            assign(index, value);
        }
        super.put(nest,index,value);
    }

    @Override
    public void put(String name, Object value) {
        Enviorment e = where(name);
        if (e == null) {
            e = this;
        }
        e.putNew(name, value);
    }

    @Override
    public Object get(String name) {
        Integer i = names.find(name);
        if (i == null) {
            if (outer == null) {
                return null;
            } else {
                outer.get(name);
            }
        }
        return values[i];
    }

    @Override
    public void putNew(String name, Object value) {
        assign(names.putNew(name),value);
    }

    @Override
    public Enviorment where(String name) {
        if (names.find(name) != null) {
            return this;
        } else if (outer == null) {
            return null;
        }
        return outer.where(name);
    }

    /**
     * 不足时进行扩容
     * @param index 索引
     * @param value 值
     */
    protected void assign(int index, Object value) {

        if (index > values.length) {
            int newLen = values.length * 2;
            if (index > newLen) {
                newLen = index + 1;
            }
            values = Arrays.copyOf(values, newLen);
        }
        values[index] = value;

    }

    /**
     *
     * @return 测试方法
     */
    public Symbols getNames() {
        return names;
    }

}
